document.addEventListener('DOMContentLoaded', function() {
    // 验证用户登录状态
    const users = JSON.parse(localStorage.getItem('registeredUsers')) || [];
    const loginEmail = localStorage.getItem('currentLoginEmail');
    
    if (!loginEmail) {
        window.location.href = 'index.html';
        return;
    }
    
    // 获取当前用户信息
    const currentUser = users.find(user => user.email === loginEmail);
    if (currentUser) {
        // 更新导航栏用户信息
        document.getElementById('user-display-name').textContent = currentUser.name || '用户';
        if (currentUser.avatar) {
            document.getElementById('header-avatar').src = currentUser.avatar;
        }
    } else {
        localStorage.removeItem('currentLoginEmail');
        window.location.href = 'index.html';
    }
    
    // 移动端菜单切换
    const mobileMenuButton = document.getElementById('mobile-menu-button');
    const mobileMenu = document.getElementById('mobile-menu');
    
    mobileMenuButton.addEventListener('click', function() {
        mobileMenu.classList.toggle('hidden');
    });
     // 用户菜单下拉功能
            const userMenuButton = document.getElementById('user-menu-button');
            const userMenuDropdown = document.getElementById('user-menu-dropdown');
            
            // 点击头像切换菜单显示/隐藏
            userMenuButton.addEventListener('click', function(event) {
                event.stopPropagation(); // 防止事件冒泡
                userMenuDropdown.classList.toggle('hidden');
            });
            
            // 点击页面其他地方关闭菜单
            document.addEventListener('click', function(event) {
                if (!userMenuButton.contains(event.target) && !userMenuDropdown.contains(event.target)) {
                    userMenuDropdown.classList.add('hidden');
                }
            });
            
            // 退出登录功能
            document.getElementById('logout-button').addEventListener('click', function() {
                localStorage.removeItem('currentLoginEmail');
                window.location.href = 'index.html';
            });
            
     updateAvatar();
    
    // 监听头像更新事件
    window.addEventListener('avatarUpdated', function(e) {
        const headerAvatar = document.getElementById('header-avatar');
        if (headerAvatar) {
            headerAvatar.src = e.detail.avatar;
        }
    });
    
    // 监听本地存储变化（应对多标签页情况）
    window.addEventListener('storage', function(e) {
        if (e.key === 'registeredUsers') {
            updateAvatar();
        }
    });
});
